package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.itheima.model.mongo.Movement;
import com.itheima.model.mongo.MovementTimeLine;
import com.itheima.model.vo.PageResult;
import com.tanhua.dubbo.utils.IdWork;
import com.tanhua.dubbo.utils.TimeService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWork idWork;

    @Autowired
    private TimeService timeService;

    @Override
    public void pushlish(Movement movement) {
        //1.保存动态详情
        movement.setPid(idWork.getNextId("movement"));
        //2.设置pid
        //3.设置时间
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);

        try {
            timeService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (InterruptedException e) {
            //忽略事务出处理
            e.printStackTrace();
        }

    }

    //查询我的动态
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //构建查询的条件
        Criteria criteria = Criteria.where("userId").is(userId);
        //根据创建时间进行降序排序
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //根据动态查询分页数据
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, 0L, movements);
    }

    /**
     * 查询当前用户好友发布的所有动态
     *
     * @param page
     * @param pageSize
     * @param friendId
     * @return
     */
    @Override
    public List<Movement> findFriendMovement(Integer page, Integer pageSize, Long friendId) {
        //1、根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1 * pageSize)).limit(pageSize).with(Sort.by(Sort.Order.desc("create")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(lineList, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情并返回
        Query movementQuery = Query.query(Criteria.where("id").in(list));
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    //根据pid查询
    @Override
    public List<Movement> findMovementByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    //随即查询多条数据
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象，设置统计参数
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //调用mongotemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //获取统计结果
        return results.getMappedResults();
    }

    //根据id查询动态详情
    @Override
    public Movement findOneMovement(String movementId) {
       return mongoTemplate.findById(movementId, Movement.class);
    }

    //根据id查询后台动态详情
    @Override
    public PageResult findByUserIdMovement(Integer page, Integer pagesize, Integer state, Long userId) {
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page -1 ) * pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, count, list);
    }

    @Override
    public Movement findByUserIdMovementInfo(String userId) {
        return mongoTemplate.findById(userId,Movement.class);
    }

}

